package it.francescogabbrielli.android.solidalapp.actions;

import android.util.Log;
import it.francescogabbrielli.android.solidalapp.Action;
import it.francescogabbrielli.android.solidalapp.EndpointsUtils;
import it.francescogabbrielli.android.solidalapp.R;
import it.francescogabbrielli.android.solidalapp.SolidalApp;
import it.francescogabbrielli.android.solidalapp.SolidalApp.DataKey;
import it.francescogabbrielli.android.solidalapp.home.HomeActivity;
import it.francescogabbrielli.android.solidalapp.requestendpoint.Requestendpoint;
import it.francescogabbrielli.android.solidalapp.requestendpoint.model.Request;

/**
 * Send a request
 */
public class EndpointsInsertRequest extends Action {
	
	Request request;

	@Override
	public void execute() throws Exception {
		
		Request temp = getModel(Request.class);
		temp.setTimestamp(System.currentTimeMillis());
		
		Requestendpoint endpoint = EndpointsUtils.buildEndpoint(Requestendpoint.class);
		request = endpoint.insertRequest(temp).execute();
		setModel(request);
		Log.d(getAction(), "Request sent: "+temp.getMessage());
	}
	
	@Override
	public void onError(String error) {
		app.setData(DataKey.REQUEST, null);
		app.alert(context.getString(R.string.request_sent_error)+"\n"+error);
	}

	@Override
	public void onPostExecute() throws Exception {
		if (request!=null) {
			Log.d(SolidalApp.TAG, "Request id: "+request.getId());
			app.setData(DataKey.REQUEST, request);
			app.alert(R.string.request_sent_message);
			refireActivity(HomeActivity.class);
		}
	}

}
